<template>
  <div class="home-container">
    <div class="slider">
      <div class="logo" :class="{ 'logo-collapsed': state.collapsed }">
        <!-- <img src="@/assets/budaidise.svg" alt=""> -->
        <img src="@/assets/NByangan.svg" alt="" />
        <span v-if="!state.collapsed">Niu Bee</span>
      </div>
      <div class="menu-container reset-scroll">
        <a-menu
          v-model:openKeys="state.openKeys"
          v-model:selectedKeys="state.selectedKeys"
          mode="inline"
          theme="dark"
          :inline-collapsed="state.collapsed"
          :items="menus"
          @select="handleMenuSelect"
        ></a-menu>
      </div>
    </div>
    <div class="content">
      <header>
        <div class="top">
          <MenuFoldOutlined class="icon-collapsed" @click="toggleCollapsed" />
        </div>
        <!--sip软电话条实现-->
        <div class="sip-main">
          <SoftPhone />
        </div>
        <a-dropdown>
          <a class="ant-dropdown-link" @click.prevent>
            <a-avatar size="small">
              <template #icon>
                <UserOutlined />
              </template>
            </a-avatar>
            <span style="margin-left: 8px">Admin ｜ 管理员</span>
          </a>
          <template #overlay>
            <a-menu @click="handleMenuClick">
              <a-menu-item key="password">
                <a href="javascript:;">修改密码</a>
              </a-menu-item>
              <a-menu-item key="logout">
                <a href="javascript:;">退出登录</a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </header>
      <div class="menu-bread">
        <a-tabs
          v-model:activeKey="activeKey"
          hide-add
          type="editable-card"
          :tab-position="mode"
          @edit="handleEdit"
          @change="handleToPath"
        >
          <a-tab-pane
            v-for="pane in chooseMenus"
            :key="pane.key"
            :tab="pane.title"
            :closable="pane.closable"
          >
          </a-tab-pane>
        </a-tabs>
      </div>
      <main>
        <RouterView />
      </main>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { handleLoginout } from '@/apis/login'
import { getUserInfo, setUserInfo, setToken } from '@/utils/local'
import { UserOutlined, MenuFoldOutlined } from '@ant-design/icons-vue'
import { getMenus } from '@/consts/menu'
import { message, type TabsProps } from 'ant-design-vue'
import SoftPhone from '@/components/SoftPhone.vue';
import { initWebsocketClient } from '@/components/WebSocketClient'
const mode = ref<TabsProps['tabPosition']>('top')
const state = reactive({
  collapsed: false,
  collapsedWidth: '256px', // 80
  selectedKeys: [0],
  openKeys: [],
  preOpenKeys: []
})
const menus = ref<any>([])
const chooseMenus = ref<{ title: any; key: string; closable?: boolean }[]>([
  { title: '首页', key: '/', closable: false }
])
const activeKey = ref('/')

const router = useRouter()

const handleChooseMenu = (path: any) => {
  activeKey.value = path
  if (path === '/') {
    state.selectedKeys = [0]
    state.openKeys = []
  }
  menus.value.forEach((item: any) => {
    if (item.children) {
      item.children.forEach((child: any) => {
        if (child.path === path) {
          state.selectedKeys = [child.key]
          state.openKeys = [item.key]
        }
      })
    }
  })
}
const handleToPath = (path: string) => {
  router.push(path)
}
const handleEdit = (targetKey: string, action: string) => {
  if (action === 'remove') {
    remove(targetKey)
  }
}
const remove = (targetKey: string) => {
  let lastIndex = 0
  chooseMenus.value.forEach((pane, i) => {
    if (pane.key === targetKey) {
      lastIndex = i - 1
    }
  })
  chooseMenus.value = chooseMenus.value.filter((pane) => pane.key !== targetKey)
  if (chooseMenus.value.length && activeKey.value === targetKey) {
    if (lastIndex >= 0) {
      activeKey.value = chooseMenus.value[lastIndex].key
    } else {
      activeKey.value = chooseMenus.value[0].key
    }
  }
  router.push(activeKey.value)
}
watch(
  () => router.currentRoute.value,
  (to, from) => {
    handleChooseMenu(to.path)
    if (to.path === '/') return
    const findItem = chooseMenus.value.find((item: any) => item.key === to.path)
    !findItem && chooseMenus.value.push({ key: to.path, title: to.meta.title })
  },
  { immediate: true }
)

const handleMenuSelect = (item: any) => {
  const path: string = item.item.path || ''
  router.push(path)
}
const toggleCollapsed = () => {
  state.collapsed = !state.collapsed
  state.openKeys = state.collapsed ? [] : state.preOpenKeys
  state.collapsedWidth = state.collapsed ? '48px' : '256px' // 64px
}

const handleMenuClick = async (menu: any) => {
  console.log(menu.key)
  if (menu.key === 'logout') {
    const res = await handleLoginout({})
    if (res.code === 200) {
      setToken('')
      setUserInfo('')
      router.push('/login')
      return
    }
    message.error(res.msg)
  }
}

onMounted(async () => {
  menus.value = await getMenus()
  handleChooseMenu(router.currentRoute.value.path)
  initWebsocketClient()
})
</script>

<style lang="less" scoped>
.home-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  background: #f0f2f5;
  overflow: hidden;
}

.slider {
  height: 100%;
  background: #001529;
}

.logo {
  height: 64px;
  color: #fff;
  display: flex;
  align-items: center;
  padding-left: 8px;

  span {
    font-size: 20px;
    padding-left: 12px;
  }
}
.menu-container {
  height: calc(100vh - 64px);
  width: v-bind('state.collapsedWidth');
  overflow-y: scroll;
  overflow-x: hidden;
  background: #001529;
  :deep(.ant-menu-inline-collapsed) {
    width: 48px !important;
  }
}

.content {
  width: calc(100vw - v-bind('state.collapsedWidth'));
  display: flex;
  flex-direction: column; /* 修改为flex布局 */
}

header {
  flex: 0 0 64px; /* 固定高度 */
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  padding: 0 16px;
  font-size: 14px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1); /* 添加阴影防止视觉断裂 */
}

.menu-bread {
  flex: 0 0 48px; /* 固定高度 */
  background: #fff;
  padding: 8px 0 0 8px;
  border-top: 1px solid #f0f0f0;
}

.sip-main {
  width: 1200px;
  height: 34px;
}

main {
  flex: 1 1 auto; /* 剩余空间全部占用 */
  padding: 8px;
  overflow-y: auto; /* 当内容过多时滚动 */
  background: #f0f2f5;
}
</style>